import logging
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from .models import registryInfo
from .models import robot_dtalk
from libs.paginations import ListPagination
from .serializers import RegistryDetailSerializer
from .serializers import RegistryCreateSerializer
from .serializers import DtalkCreateSerializer
from .serializers import DtalkDetailSerializer
from libs.dtalk import Dtalk_Message


CUSTOM_ERROR = logging.getLogger('apps.views')



class RegistryViewSet(viewsets.ModelViewSet):
    '''镜像仓库'''

    queryset = registryInfo.objects.all()
    pagination_class = ListPagination
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)

    def get_serializer_class(self):
        if self.action == 'create' or self.action == 'update':
            return RegistryCreateSerializer
        return RegistryDetailSerializer



class RegistryConnectStatusApiView(APIView):
    '''测试镜像仓库远程连接,传参：{'id':int}'''

    def connect_staus_registry(self, repo_id):
        from docker import APIClient
        try:
            # C = APIClient(base_url='unix:///var/run/docker.sock', timeout=5)
            C = APIClient(base_url='http://192.168.10.204:2375', timeout=5)
            instance = registryInfo.objects.filter(id=repo_id).values().first()
            C.login(username=instance['username'], password=instance['password'], registry=instance['registry'])
        except TimeoutError as e:
            CUSTOM_ERROR.error(f'{e.__class__.__name__}: {e}')
            return {'msg':'远程连接失败,%s'%str(e)}
        else:
            return {'msg':'连接成功!'}

    def get(self,request,format=None):
        repo_id=self.request.query_params['id']
        return Response(self.connect_staus_registry(repo_id))


class RobotDtalkViewSet(viewsets.ModelViewSet):
    '''钉钉机器人设置'''

    queryset = robot_dtalk.objects.all()
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)

    def get_serializer_class(self):
        if self.action == 'list' or self.action == 'retrieve':
            return DtalkDetailSerializer
        return DtalkCreateSerializer



class RobotConnectApiView(APIView):
    '''机器人测试'''
    def get(self,request,*args,**kwargs):
        intance = robot_dtalk.objects.filter(**kwargs).values().first()
        robot = Dtalk_Message(webhook=intance.get('webhook'))
        return Response(robot.robot_test(robot_name=intance.get('robot_name')))